package com.xp.basic.heima.nio.netty.simpledemo.worker;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Arrays;
import java.util.Scanner;

public class TestNettyHandleClient {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        Channel channel = new Bootstrap()
                .group(eventLoopGroup)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder());
                        ch.pipeline().addLast(new ChannelOutboundHandlerAdapter(){
                            @Override
                            public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
                                System.out.println(Thread.currentThread().getName() + "调用 write ");
                                super.write(ctx, msg, promise);
                            }
                        });
                        ch.pipeline().addLast(new ChannelOutboundHandlerAdapter(){
                            @Override
                            public void flush(ChannelHandlerContext ctx) throws Exception {
                                System.out.println(Thread.currentThread().getName() + "调用 flush ");
                                super.flush(ctx);
                            }
                        });
                    }
                })
                .connect("localhost", 8080)
                .sync()
                .channel();
        int a = 0;
        while (true){
            System.out.println("请输入：");
            Scanner scanner = new Scanner(System.in);
            String next = scanner.next();

            if ("q".equals(next)) {
                channel.close();
                //优雅得关闭
                eventLoopGroup.shutdownGracefully();
                break;
            }

            channel.write(next);
            a++;
            if(a == 3){
                channel.flush();
                a = 0;
            }
        }

    }
}
